import { defineStore } from "pinia";
import { reqLogin, reqLogout, reqUserInfo } from "@/api/user";
import { constantRoute } from "@/router/routes";
import type { UserState } from "./types/type";
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from "../../utils/token";
import { loginFormData,loginResponseData,userInfoReponseData } from '../../api/user/type';


let useUserStore = defineStore("User", {
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute, //存储路由数组
      username: "",
      avatar: "",
    };
  },
  actions: {
    async userLogin(data: loginFormData) {
      let result: loginResponseData = await reqLogin(data);

      if (result.code == 200) {
        this.token = result.data as string;
        SET_TOKEN(result.data);
        return "ok"; //返回一个成功的promise
      } else {
        return Promise.reject(new Error(result.data));
      }
    },
    async userInfo() {
      //获取用户信息并存储
      let res:userInfoReponseData = await reqUserInfo();
      if (res.code == 200) {
        this.username = res.data.name;
        this.avatar = res.data.avatar;
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
    async userLogout() {
      //退出接口、通知服务器本次token失效
      let res:any = await reqLogout();
      if (res.code == 200) {
        this.token = "";
        this.username = "";
        this.avatar = "";
        REMOVE_TOKEN();
        return "ok";
      } else {
        return Promise.reject(new Error(res.message));
      }
    },
  },
  getters: {},
});

export default useUserStore;
